/* 
    利用 art-template 实现动态网站
*/
const http = require('http');
const fs = require('fs');
const path = require('path');
const template = require('art-template');
const querystring = require('querystring');
const scores = require('./scores.json');

http.createServer((req,res)=>{
    // 查询成绩 /query
    if ( req.url.startsWith('/query') && req.method == 'GET' ) {
        let data = template(path.join(__dirname,'view','index.html'),{});
        res.end(data);
    }
    // 获得成绩 /score
    else if ( req.url.startsWith('/score') && req.method == 'POST' ) {
        let pdata = '';
        req.on('data',(chunk)=>{
            pdata += chunk;
        });
        req.on('end',()=>{
            let obj = querystring.parse(pdata);
            let resultData = scores[obj.code];
            let data = template(path.join(__dirname,'view','result.html'),resultData);
            res.end(data);
        });
    }
    // 查看全部成绩 /all
    else if ( req.url.startsWith('/all') && req.method == 'GET' ) {
        let arr = [];
        for ( let items in scores ) {
            arr.push(scores[items]);
        }
        let data = template(path.join(__dirname, 'view', 'list.html'),{
            list: arr
        });
        res.end(data);
    }
    
}).listen(1000,()=>{
    console.log('running……');
});







